// ignore_for_file: use_build_context_synchronously

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:image_picker/image_picker.dart';

import '../../conctroller/UserInfoController.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 1. 从GetX中获取用户信息控制器
  UserInfoController controller = Get.find<UserInfoController>();

  // 输入框控制器
  TextEditingController nicknameController = TextEditingController();
  String tempAvatar = "";
  String tempFileName = ""; // 用来临时存储头像的文件名称// 用来临时存储头像的变量
  /// 保存用户信息
  // 保存用户信息
  _saveUserInfo() async {
    if (nicknameController.text.isEmpty) {
      PromptAction.showWarning("用户昵称不能为空");
      return;
    }
    if (!RegExp(r'^[\u4e00-\u9fa5]{2,10}').hasMatch(nicknameController.text)) {
      PromptAction.showWarning("昵称必须是2-10个中文字符");
      return;
    }
    var avatar = controller.userInfo["avatar"] ?? ""; // 原来的地址
    // 判断是否需要上传头像 上传完头像再进行保存用户信息 拿到上传的地址 =》 保存接口 存储到用户的头像上
    if (tempAvatar.isNotEmpty) {
      // 要进行上传

      Uint8List list = await XFile(tempAvatar).readAsBytes(); // 读取二进制
      // 要得到file对象
      MultipartFile file =
          MultipartFile.fromBytes(list, filename: tempFileName);
      FormData data =
          FormData.fromMap({"file": file, "type": 'avatar'}); // 得到formData类型

      final res = await uploadPhotoAPI(data);
      avatar = res["url"]; // 上传成功的地址
    }

    await updateUserInfoAPI({
      "nickName": nicknameController.text,
      "avatar": avatar,
    });
    // 认为任务已经完成啦
    tempAvatar = "";
    tempFileName = "";
    // controller 此时共享需要更新

    // 提示一下
    PromptAction.showSuccess("用户资料保存成功");
    controller.userInfo["nickName"] = nicknameController.text; // 更新对象里面的属性
    controller.userInfo["avatar"] = avatar; // 更新对象里面的属性
    controller.updateUserInfo(controller.userInfo); // 通过Getx的更新方法驱动页面进行更新
    //返回
    Navigator.of(context).pop();
  }

  /// 显示选择头像弹窗
  showSheet() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return Container(
            height: 150,
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: [
                getCamera(),
                getLibrary(),
                getCancel(),
              ],
            ),
          );
        });
  }

//打开项目
  openLibrary() async {
    // 1. 实例化一个ImagePicker
    ImagePicker picker = ImagePicker();
    XFile? file = await picker.pickImage(source: ImageSource.gallery);
    if (file != null) {
      tempAvatar = file.path;
      tempFileName = file.name;
      setState(() {});
      Navigator.pop(context);
    }
  }

  /// 拍照
  Widget getCamera() {
    return SizedBox(
      height: 50,
      child: GestureDetector(
          onTap: () {},
          child: Container(
            decoration: const BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.grey,
                  width: 0.5,
                ),
              ),
            ),
            child: const Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.camera_alt),
                SizedBox(
                  width: 10,
                ),
                Text("拍照")
              ],
            ),
          )),
    );
  }

  /// 相册
  Widget getLibrary() {
    return SizedBox(
      height: 50,
      child: GestureDetector(
        onTap: () {
          openLibrary();
        },
        child: Container(
          decoration: const BoxDecoration(
              border: Border(
            bottom: BorderSide(
              color: Colors.grey,
              width: 0.5,
            ),
          )),
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.photo_library),
              SizedBox(
                width: 10,
              ),
              Text("相册")
            ],
          ),
        ),
      ),
    );
  }

  /// 取消
  Widget getCancel() {
    return GestureDetector(
      onTap: () {
        Navigator.pop(context);
      },
      child: const SizedBox(
        height: 50,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.cancel),
            SizedBox(
              width: 10,
            ),
            Text("取消")
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    // 初始化输入框控制器
    nicknameController.text = controller.userInfo['nickName'] ?? '';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        showSheet();
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: getUserAvatar(),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: nicknameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () async {
                    await _saveUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  Widget getUserAvatar() {
    if (tempAvatar.isNotEmpty) {
      // web场景下是network
      // 鸿蒙安卓 相册路径 file://
      if (kIsWeb) {
        return Image.network(
          tempAvatar,
          width: 30,
          height: 30,
        );
      }
      // 除了web平台 都采用file图片的形式
      return Image.file(
        File(tempAvatar),
        width: 30,
        height: 30,
      );
    }
    if (controller.userInfo['avatar'] != '' &&
        controller.userInfo['avatar'] != null) {
      return Image.network(
        controller.userInfo['avatar'],
        width: 30,
        height: 30,
        fit: BoxFit.cover,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
      fit: BoxFit.cover,
    );
  }
}
